<template>
  <!-- 创建二级分类 -->
  <div class="product_two">
    <el-form
      :model="numberValidate"
      ref="numberValidate"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 绑定一级类别 -->
      <el-form-item label="所属类别:" prop="pic">
        <el-select v-model="numberValidate.typeOneId" placeholder="请选择类别">
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.typeOne"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="品牌"
        prop="typeTwo"
        :rules="[{ required: true, message: '分类不能为空' }]"
      >
        <el-input
          type="typeOne"
          v-model="numberValidate.typeTwo"
          placeholder="请输入品牌 如 小米、华为"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <!-- 添加图片 -->
      <el-form-item label="分类图片:" prop="img">
        <el-upload
          class="avatar-uploader"
          action=""
          accept="image/jpg,image/png,image/jpeg"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="imgBroadcastChange"
        >
          <img
            v-if="numberValidate.Img"
            :src="numberValidate.Img"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitType('numberValidate')"
          >添加</el-button
        >
        <el-button :loading="loading" @click="resetType('numberValidate')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProduct } from "@/api/product";
import { addTypeTwo } from "@/api/typeTwo";

export default {
  data() {
    return {
      //二类
      numberValidate: {
        typeTwo: "",
        Img: "",
        typeOneId: "",
      },
      //获取一级类型，渲染下拉列表
      options: [],
      loading: false,
    };
  },
  created() {
    this.getTypeOne();
  },
  methods: {
    getTypeOne() {
      //获取一级分类列表
      getProduct().then((res) => {
        this.options = res;
      });
    },
    //添加二级分类
    submitType(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          addTypeTwo(this.numberValidate).then(() => {
            this.loading = false;
            this.$message("添加成功");
            this.$refs[formName].resetFields();
            this.$router.replace({ name: "typeTwoList" });
          });
        }
      });
    },
    //图片
    //限制图片大小
    imgBroadcastChange(file, fileList) {
      console.log(file.size);
      const isLt1M = file.size / 1024 / 1024 < 1;
      console.log(isLt1M);
      if (isLt1M) {
        // uploadImgToBase64()返回一个Promise对象，通过.then()获取其数据。其中data.result是图片转成的base64值
        this.uploadImgToBase64(file.raw).then((data) => {
          this.numberValidate.Img = data.result;
        });
      } else {
        this.$message.error("上传封面图片大小不能超过 1MB!");
      }
    },
    //将上传的图片转换成Base64
    uploadImgToBase64(file) {
      //核心方法，将图片转成base64字符串形式
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
          // 图片转base64完成后返回reader对象
          resolve(reader);
        };
        reader.onerror = reject;
      });
    },
    resetType(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.product_two {
  margin-top: 50px;
  margin-left: 20%;
  width: 30%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>